package linearstructure.linkedlist.circlelist;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-26 15:12
 * @ Description :
 */
public class CircleList
{
    private Boy first = null;

    //添加
    public void addBoy(int nums)
    {
        if (nums < 1)
        {
            System.out.println("至少需要1个编号");
            return;
        }
        Boy cur = null;//指向当前boy
        for (int i = 1; i <= nums; i++)
        {
            Boy boy = new Boy(i);

            if (i == 1)
            {
                first = boy;
                first.setNext(first);
            }
            else
            {
                cur.setNext(boy);
                boy.setNext(first);
            }
            cur = boy;
        }
    }

    //遍历
    public void showBoy()
    {
        if (first == null)
        {
            System.out.println("链表为空");
            return;
        }
        Boy cur = first;
        while (true)
        {
            System.out.printf("编号为%d\n", cur.getNo());
            if (cur.getNext() == first)
            {
                break;
            }
            cur = cur.getNext();
        }
    }

    /**
     * @param start: 开始计数的boy编号, countNum: 数到countNum结束, nums: boy总数
     * @return void
     * @Description 约瑟夫环
     **/
    public void countBoy(int start, int countNum, int nums)
    {
        if (first == null || start < 1 || start > nums)
        {
            System.out.println("参数输入错误");
            return;
        }
        Boy helper = first;
        while (helper.getNext() != first)
        {
            helper = helper.getNext();
        }

        //移动k-1次
        for (int i = 0; i < start - 1; i++)
        {
            first = first.getNext();
            helper = helper.getNext();
        }

        while (helper != first)
        {
            //移动countNum-1次
            for (int i = 0; i < countNum - 1; i++)
            {
                first = first.getNext();
                helper = helper.getNext();
            }
            System.out.printf("编号为%d退出\n", first.getNo());
            //出圈
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后一人的编号为: %d",first.getNo());
    }


}
